<template>
  <div>
    <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm" status-icon>
      <el-row>
        <el-col :span="12">
          <el-form-item label="关联项目" prop="projectName">
            <el-input v-model="ruleForm.projectName"  placeholder="请选择" style="width: 250px;"  disabled="1" >
              <template #append>
<!--                <el-button type="primary" @click="open">选择</el-button>-->
              </template>
            </el-input>
            <!-- <div class="content-box">
            <div class="select">请选择</div>
            <el-button type="text" @click="open">选择</el-button>
          </div> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属单位" prop="unitId">
            <popup-tree-input :data="orgAllList" :props="deptForm.popupTreeProps" :prop="deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : ruleForm.unitName
                        " :node-key="'' + deptForm.parentId" :current-change-handle="changeUnit" :disabled="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="关联合同" prop="associateContract">
            <el-input v-model="ruleForm.associateContract"  placeholder="请选择" style="width: 250px;" :disabled="1">
              <template #append>
<!--                <el-button type="primary" @click="open2">选择</el-button>-->
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="业务名称" prop="kpiName">
            <el-input v-model="ruleForm.kpiName" placeholder="请输入" :disabled="1" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="转化类别" prop="classTransId">
            <el-select v-model="ruleForm.classTransId" placeholder="请选择" style="width: 250px" @change="changeClasss"  :disabled="1">
              <el-option :label="el.text" :value="el.value" :key="k" v-for="(el, k) in options.projectnameList"  :disabled="1"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="转化金额" prop="transAmount">
            <el-input type="number" v-model.number="ruleForm.transAmount" min="0" placeholder="请输入" :disabled="1">
              <template #append> 万元 </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="转化年度" prop="transYearId">
            <el-select v-model="ruleForm.transYearId" placeholder="请选择" style="width: 250px" :disabled="1">
              <el-option :label="item" :value="item" :key="item" v-for="item in options.budgetYearlist" :disabled="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item style="display: flex; justify-content: flex-end;">
            <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            <el-button @click="closeFatherDialog">关闭</el-button>
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <!-- 项目弹窗 -->
    <el-dialog v-model="dialogVisible" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="项目选择" name="first">
              <div class="search-box">
                <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                  style="width: 300px" >
                  <template #append>
                    <el-button type="primary" @click="open">搜索</el-button>
                  </template>
                </el-input>
              </div>
              <el-table :data="options.xiangmuList" style="width: 100%" border @selection-change="handleSelectionChange1">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="projectName" label="项目名称" />
                <el-table-column prop="projectNumber" label="项目编号" />
                <el-table-column prop="startTime" label="起止时间" />
                <el-table-column prop="formerName" label="项目负责人" />
                <el-table-column prop="projectApplication" label="项目承担单位" />
              </el-table>
              <div class="example-pagination-block">
                <el-pagination
                  background
                  layout="prev, pager, next ,total,sizes,jumper"
                  :total="options.total"
                  :page-size="xiangmuParams.size"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
          <div class="handle">
            <el-button color="#626aef" @click="dialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="toHandle1">关联</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 合同弹窗 -->
    <el-dialog v-model="dialogVisible2" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="项目选择" name="first">
              <div class="search-box">
                <el-input v-model="hetongParams.contractName" placeholder="请输入" class="input-with-select"
                  style="width: 300px">
                  <template #append>
                    <el-button type="primary" @click="open2">搜索</el-button>
                  </template>
                </el-input>
              </div>
              <el-table :data="options.hetongList" style="width: 100%" border @selection-change="handleSelectionChange2">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="contractName" label="合同名称" />
                <el-table-column prop="projectNumber" label="合同编号" />
                <el-table-column prop="startTime" label="起止时间" />
                <el-table-column prop="formerName" label="合同负责人" />
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <div class="handle">
            <el-button color="#626aef" @click="dialogVisible2 = false">关闭</el-button>
            <el-button type="primary" @click="toHandle2">关联</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Api from '@/views/science/api/profess'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import { tips } from '@/views/science/components/tips/tips'
import { ElMessage } from 'element-plus'
import { reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import {
contractManagementListPage,
projectManagementListPage
} from '../api/technologyStrength'
export default {
  components: {
    PopupTreeInput,
    // SelectOption,
  },
  props: {
    orgAllList: {
      type: Array,
      required: true,
    },
    initData: {
      type: Object,
      required: true,
    },
    initNum: {
      type: Object,
    },
  },
  setup(props, context) {

    const deptForm = {
      parentId: 0,
      parentName: '',
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },
    }

    // 提交表单-字段对照新增接口-然后同步
    let ruleForm = reactive({
      id: '',
      projectId: '', //项目id
      projectName: '', //项目名称
      associateContractId: '', //合同id
      associateContract: '', //合同名称
      unitId: '',
      unitName: '',
      lockflag: "0",
      kpiName: '',
      classTransId: '',
      classTransName: '',
      transAmount: '',
      transYearId: '',
      transYear: '',
      // list: [{
      //   url: '',
      //   urlname: '',
      //   urllx: '',
      //   urldx: ''
      // }],
    })
    //项目搜索参数
    let xiangmuParams = reactive({
      projectName: '',
      projectNumber: '',
      createOrgId: '',
      level: '',
      current: 1,
      size: 20,
      projectCategory: '1',
    })
    //合同搜索参数
    let hetongParams = reactive({
      projectName: '',
      projectMainDataCode: '',
      contractName: '',
      contractNumber: '',
      current: 1,
      size: 10,
    })

    // let ruleForm = reactive({ ...props.initNum })
    // console.log(props.initData, 'initData');
    // console.log(props.initNum, 'initNum');

    watch(
      () => props.initData,
      (newValue, oldValue) => {
        if (JSON.stringify(newValue) !== '{}') {
          for (let key in ruleForm) {
            for (let key2 in newValue) {
              if (key === key2) {
                ruleForm[key] = newValue[key2]
              }
            }
          }
        } else {
          for (let key in ruleForm) {
            ruleForm[key] = ''
          }
        }
      },
      { deep: true, immediate: true }
    )
    const rules = reactive({
      projectName: [{ required: true, message: '请选择', trigger: 'change' }],
      unitId: [{ required: true, message: '请选择', trigger: 'change' }],
      associateContract: [{ required: true, message: '请选择', trigger: 'change' }],
      kpiName: [{ required: true, message: '请输入', trigger: 'change' }],
      classTransId: [{ required: true, message: '请选择', trigger: 'change' }],
      transAmount: [{ required: true, message: '请输入', trigger: 'change' }],
      transYearId: [{ required: true, message: '请选择', trigger: 'change' }],
    })
    // 弹窗中的选择
    let options = reactive({
      xiangmuList: [], //项目列表
      hetongList: [], //合同列表
      projectList: [],
      contractList: [],
      unitnameList: [] as any,
      budgetYearlist: [] as any,
      projectnameList: [] as any,
      total:0,
    })
    //所属单位change
    const changeUnit = (item) => {
      ruleForm.unitName = item.name
      ruleForm.unitId = item.id
    }

    const calculaTime = () => {

      const currentYear: number = new Date().getFullYear();

      // 构建年份数组
      const years: number[] = [];

      // 获取前三年的年份
      for (let i: number = 3; i >= 1; i--) {
        years.push(currentYear - i);
      }
      // 获取当前年份
      years.push(currentYear);
      // 获取后三年的年份
      for (let i: number = 1; i <= 3; i++) {
        years.push(currentYear + i);
      }
      options.budgetYearlist = years

  }
    const start = () => {

    calculaTime()


    // 项目列表
    Api.getProjectList().then((res) => {
      // console.log('项目列表', res.data.data)
      options.projectList = res.data.data
    })
    // 合同列表
    Api.getContractList().then((res) => {
      options.contractList = res.data.data
    })
    // 年份
    // Api.transyear().then((res) => {
    //   if (res.data.data.length > 0) {
    //     options.budgetYearlist = res.data.data
    //   }
    // })
    // 单位
    Api.unitname().then((res) => {
      options.unitnameList = res.data.data
    })
    // 转化类别
    Api.getDictByCode({ code: 'KJSL_CONVERSION_CATEGORY' }).then((res) => {
      options.projectnameList = res.data.data
    })
  }
    start()

    const ruleFormRef = ref()
    const submitForm = async () => {
    return new Promise((resolve, reject) => {
      ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          ruleForm.transYear = ruleForm.transYearId
          resolve(ruleForm)
        } else {
          ElMessage({
            message: '请将基本信息补充完整',
            type: 'warning',
          })
          // reject()
        }
      })
    })

    // if (ruleForm.id) {
    //   const res = await kgptKjslTchieveSttransUpdate(ruleForm)
    //   tips('修改成功', 'success')
    // } else {
    //   console.log("入参", ruleForm)
    //   const res = await kgptKjslTchieveSttransInsert(ruleForm)
    //   tips('新增成功', 'success')
    // }
    // closeFatherDialog()
  }

    const store = useStore()
    const labelPosition = ref('right')
    const data = reactive({
    activeName: ref('first'),
    addUnit: false,
    innerValue: '',
    outsideValue: '',
  })
    const textarea2 = ref('')
    const form = reactive(store.state.technologyStrength.form)

    const changeValue = (item) => (form.headBy = item.value)
    const changeValue1 = (item) => (form.reField = item.value)
    const changeValue2 = (item) => (form.conUnit = item.value)
    const changeValue3 = (item) => (form.level = item.value)

    const changeClasss = (id) => {

    let itemText = options.projectnameList.find((item) => item.value == id).text;

    ruleForm.classTransName = itemText


  }




    let activeName = ref('first')
    let dialogVisible = ref(false)
    let dialogVisible2 = ref(false)
    let isShow = ref(false)
    let isProject = ref(false)
    //项目列表
    let open = async () => {
      const res = await projectManagementListPage(xiangmuParams)
      const rs = res.data.data
      options.xiangmuList = rs.records
      options.total = rs.total
      dialogVisible.value = true
    }
    //改变页码
    const handleCurrentChange = (e) => {
      xiangmuParams.current = e
      open()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      xiangmuParams.size = e
      open()
    }

    //合同列表
    let open2 = async () => {
    const res = await contractManagementListPage(hetongParams)
    const rs = res.data.data
    options.hetongList = rs.records
    dialogVisible2.value = true
  }

    let changeList = ref([])

    let select1 = ref([]) //项目
    let select2 = ref([]) //合同

    const toHandle1 = () => {
    if (select1.value.length != 1) {
      tips('请选择一项关联', 'warning')
      return
    } else {
      let obj = select1.value[0]
      ruleForm.projectId = (obj as any).id
      ruleForm.projectName = (obj as any).projectName
      dialogVisible.value = false
    }
  }
    const toHandle2 = () => {
    if (select2.value.length != 1) {
      tips('请选择一项关联', 'warning')
      return
    } else {
      let obj = select2.value[0]
      ruleForm.associateContractId = (obj as any).id
      ruleForm.associateContract = (obj as any).contractName
      dialogVisible2.value = false
    }
  }
    let handleSelectionChange1 = (val) => {
    select1.value = val
  }
    let handleSelectionChange2 = (val) => {
    select2.value = val
  }
    let closeFatherDialog = () => {
    context.emit('closeFatherDialog')
  }

    return {
    deptForm,
    xiangmuParams,
    hetongParams,
    closeFatherDialog,
    ruleForm,
    rules,
    toHandle1,
    toHandle2,
    ruleFormRef,
    changeClasss,
    open,
    open2,
    handleCurrentChange,
    handleSizeChange,
    dialogVisible,
    dialogVisible2,
    isShow,
    isProject,
    activeName,
    changeList,
    handleSelectionChange1,
    handleSelectionChange2,
    calculaTime,

    labelPosition,
    data,
    form,
    options,
    textarea2,
    submitForm,
    changeValue,
    changeValue1,
    changeValue2,
    changeValue3,
    changeUnit
  }
},
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.content-box {
  width: 250px;
  height: 33px;
  padding: 5px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select {
  color: #eee;
}

.align-center {
  align-items: center;
}

.space-between {
  justify-content: space-between;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
}

.handle {
  position: absolute;
  top: 17px;
  right: 20px;
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 10px;
}
</style>
